package com.anti.core.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2020-10-21
 */
@Component
public class PropertyPlaceholderConfigurer  implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;
    private Map propertyMap=new HashMap();
    @Override
    public void afterPropertiesSet() throws Exception {
        Environment environment = applicationContext.getEnvironment();
        Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
        for (ConfigurationPropertySource source : sources) {
            Object underlyingSource = source.getUnderlyingSource();
            if (underlyingSource instanceof OriginTrackedMapPropertySource){
                OriginTrackedMapPropertySource originSource= (OriginTrackedMapPropertySource) underlyingSource;
                Map<String, Object> sourceMap = originSource.getSource();
                Iterator<Map.Entry<String, Object>> iterator = sourceMap.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry<String, Object> next = iterator.next();
                    String key = next.getKey();
                    if (key.startsWith(PropertyConstants.PREFIX)){
                        OriginTrackedValue value = (OriginTrackedValue) next.getValue();
                        propertyMap.put(key,value.getValue().toString());
                    }
                }
            }
        }
        PropertyHelper.initPropertyMap(propertyMap);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
